import React, { useState, useEffect } from 'react'
import { Download } from 'lucide-react'
import { keyPartsAPI } from '../services/api'

const KeyPartsInventory = () => {
  // 表格行数
  const [tableRows, setTableRows] = useState(20)
  
  // 固定列名配置
  const columnNames = ['序号', '物品名称', '型号', '入库数量', '入库时间', '库存数量', '领用数量', '领用时间', '用途', '领用人', '备注']
  const tableCols = columnNames.length
  
  // 表格数据
  const [tableData, setTableData] = useState([])
  
  // 输入控制状态
  const [rowInput, setRowInput] = useState('20')
  
  // 加载状态
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)
  
  // 存储原始数据库数据
  const [dbData, setDbData] = useState([])
  
  // 加载数据从后端
  const loadDataFromAPI = async () => {
    try {
      setLoading(true)
      setError(null)
      const response = await keyPartsAPI.getAll()
      const data = response.results || []
      setDbData(data)
      
      // 转换API数据为表格格式
      const convertedData = data.map((item, index) => [
        index + 1, // 序号
        item.item_name || '',
        item.model || '',
        item.stock_in_quantity || 0,
        item.stock_in_time ? item.stock_in_time.split(' ')[0] : '', // 只取日期部分
        item.inventory_quantity || 0,
        item.used_quantity || 0,
        item.used_time ? item.used_time.split(' ')[0] : '', // 只取日期部分
        item.purpose || '',
        item.user_name || '',
        item.remarks || ''
      ])
      
      // 使用数据库数据
      setTableData(convertedData)
      setTableRows(convertedData.length)
      setRowInput(convertedData.length.toString())
    } catch (err) {
      console.error('加载数据失败:', err)
      setError('加载数据失败，请检查网络连接')
    } finally {
      setLoading(false)
    }
  }
  
  // 组件挂载时加载数据
  useEffect(() => {
    loadDataFromAPI()
  }, [])

  // 导出Excel功能 - 导出当前界面内容
  const exportToExcel = () => {
    // 创建CSV内容
    const csvContent = [
      columnNames.join(','),
      ...tableData.map(row => 
        row.map(cell => `"${cell || ''}"`).join(',')
      )
    ].join('\n')

    // 添加BOM以支持中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    
    // 生成文件名
    const now = new Date()
    const dateStr = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0')
    link.setAttribute('download', `关键备件库存记录表_${dateStr}.csv`)
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  // 更新表格数据
  const updateTableData = (rowIndex, colIndex, value) => {
    setTableData(prev => {
      const newData = [...prev]
      newData[rowIndex] = [...newData[rowIndex]]
      newData[rowIndex][colIndex] = value
      return newData
    })
  }
  
  // 验证行数据
  const validateRowData = (row, rowIndex) => {
    const errors = []
    
    // 检查物品名称
    if (!row[1] || row[1].trim() === '') {
      errors.push(`第${rowIndex + 1}行：物品名称不能为空`)
    }
    
    // 检查数字字段
    const numberFields = [
      { index: 3, name: '入库数量' },
      { index: 5, name: '库存数量' },
      { index: 6, name: '领用数量' }
    ]
    
    numberFields.forEach(field => {
      const fieldValue = row[field.index]
      if (fieldValue !== '' && fieldValue !== null && fieldValue !== undefined) {
        const value = parseInt(fieldValue)
        if (isNaN(value) || value < 0) {
          errors.push(`第${rowIndex + 1}行：${field.name}必须是非负整数`)
        }
      }
    })
    
    // 检查日期格式（简单验证）
    const dateFields = [
      { index: 4, name: '入库时间' },
      { index: 7, name: '领用时间' }
    ]
    
    dateFields.forEach(field => {
      const fieldValue = row[field.index]
      if (fieldValue && String(fieldValue).trim() !== '') {
        const dateStr = String(fieldValue).trim()
        // 更宽松的日期格式验证，支持多种格式
        const dateRegex = /^\d{4}[-/]\d{1,2}[-/]\d{1,2}$/
        const isValidDate = dateRegex.test(dateStr) || !isNaN(Date.parse(dateStr))
        if (!isValidDate) {
          errors.push(`第${rowIndex + 1}行：${field.name}格式不正确，请使用有效的日期格式`)
        }
      }
    })
    
    return errors
  }
  
  // 保存单行数据到数据库
  const saveRowToDatabase = async (rowIndex) => {
    try {
      const row = tableData[rowIndex]
      if (!row || row.length < 11) return { success: false, errors: ['数据格式错误'] }
      
      // 检查是否有必要的数据（至少物品名称不为空）
      if (!row[1] || row[1].trim() === '') {
        return { success: true, skipped: true } // 空行跳过
      }
      
      // 验证数据
      const validationErrors = validateRowData(row, rowIndex)
      if (validationErrors.length > 0) {
        return { success: false, errors: validationErrors }
      }
      
      const keyPartData = {
        item_name: row[1].trim(),
        model: row[2].trim(),
        stock_in_quantity: row[3] !== '' && row[3] !== null && row[3] !== undefined ? parseInt(row[3]) : 0,
        stock_in_time: row[4] && String(row[4]).trim() ? String(row[4]).trim() + 'T00:00:00Z' : null,
        inventory_quantity: row[5] !== '' && row[5] !== null && row[5] !== undefined ? parseInt(row[5]) : 0,
        used_quantity: row[6] !== '' && row[6] !== null && row[6] !== undefined ? parseInt(row[6]) : 0,
        used_time: row[7] && String(row[7]).trim() ? String(row[7]).trim() + 'T00:00:00Z' : null,
        purpose: row[8].trim(),
        user_name: row[9].trim(),
        remarks: row[10].trim()
      }
      
      // 检查是否是更新现有记录
      const existingItem = dbData[rowIndex]
      if (existingItem && existingItem.id) {
        // 更新现有记录
        await keyPartsAPI.update(existingItem.id, keyPartData)
      } else {
        // 创建新记录
        const newItem = await keyPartsAPI.create(keyPartData)
        // 更新本地数据库数据
        setDbData(prev => {
          const newDbData = [...prev]
          newDbData[rowIndex] = newItem
          return newDbData
        })
      }
      
      return { success: true }
    } catch (err) {
      console.error('保存数据失败:', err)
      return { success: false, errors: [`第${rowIndex + 1}行保存失败: ${err.message || '网络错误'}`] }
    }
  }
  
  // 保存所有数据到数据库
  const saveAllToDatabase = async () => {
    try {
      setLoading(true)
      setError(null)
      
      const results = []
      let successCount = 0
      let skipCount = 0
      const allErrors = []
      
      for (let i = 0; i < tableData.length; i++) {
        const result = await saveRowToDatabase(i)
        results.push(result)
        
        if (result.success) {
          if (result.skipped) {
            skipCount++
          } else {
            successCount++
          }
        } else {
          allErrors.push(...result.errors)
        }
      }
      
      // 显示结果
      if (allErrors.length > 0) {
        const errorMessage = `保存完成，但有错误：\n${allErrors.join('\n')}`
        setError(errorMessage)
      } else {
        setError(null)
      }
      
      // 重新加载数据以确保同步
      if (successCount > 0) {
        await loadDataFromAPI()
      }
    } catch (err) {
      console.error('批量保存失败:', err)
      setError('批量保存失败，请检查网络连接')
    } finally {
      setLoading(false)
    }
  }
  
  // 删除行并同步到数据库
  const deleteRow = async (rowIndex) => {
    try {
      const existingItem = dbData[rowIndex]
      if (existingItem && existingItem.id) {
        // 从数据库删除
        await keyPartsAPI.delete(existingItem.id)
      }
      
      // 从本地状态删除
      setTableData(prev => {
        const newData = prev.filter((_, index) => index !== rowIndex)
        // 重新编号
        return newData.map((row, index) => {
          const newRow = [...row]
          newRow[0] = index + 1
          return newRow
        })
      })
      
      setDbData(prev => prev.filter((_, index) => index !== rowIndex))
      setTableRows(prev => prev - 1)
      setRowInput((prev) => (parseInt(prev) - 1).toString())
      
    } catch (err) {
      console.error('删除数据失败:', err)
      setError('删除数据失败，请检查网络连接')
    }
  }



  // 更新行数
  const updateRowCount = () => {
    const newRowCount = parseInt(rowInput)
    if (isNaN(newRowCount) || newRowCount < 1) {
      alert('请输入有效的行数（大于0的整数）')
      return
    }
    setTableRows(newRowCount)
    setTableData(prev => {
      if (newRowCount > prev.length) {
        // 增加行
        const additionalRows = Array.from({ length: newRowCount - prev.length }, (_, index) => 
          Array.from({ length: tableCols }, (_, colIndex) => 
            colIndex === 0 ? prev.length + index + 1 : ''
          )
        )
        return [...prev, ...additionalRows]
      } else {
        // 减少行
        return prev.slice(0, newRowCount).map((row, index) => {
          const newRow = [...row]
          newRow[0] = index + 1 // 重新编号
          return newRow
        })
      }
    })
  }

  // 鼠标拖拽滚动功能
  useEffect(() => {
    const tableContainer = document.querySelector('.inventory-table-container')
    if (!tableContainer) return

    let isDown = false
    let startX
    let scrollLeft

    const handleMouseDown = (e) => {
      isDown = true
      tableContainer.style.cursor = 'grabbing'
      startX = e.pageX - tableContainer.offsetLeft
      scrollLeft = tableContainer.scrollLeft
    }

    const handleMouseLeave = () => {
      isDown = false
      tableContainer.style.cursor = 'grab'
    }

    const handleMouseUp = () => {
      isDown = false
      tableContainer.style.cursor = 'grab'
    }

    const handleMouseMove = (e) => {
      if (!isDown) return
      e.preventDefault()
      const x = e.pageX - tableContainer.offsetLeft
      const walk = (x - startX) * 2
      tableContainer.scrollLeft = scrollLeft - walk
    }

    tableContainer.addEventListener('mousedown', handleMouseDown)
    tableContainer.addEventListener('mouseleave', handleMouseLeave)
    tableContainer.addEventListener('mouseup', handleMouseUp)
    tableContainer.addEventListener('mousemove', handleMouseMove)

    return () => {
      tableContainer.removeEventListener('mousedown', handleMouseDown)
      tableContainer.removeEventListener('mouseleave', handleMouseLeave)
      tableContainer.removeEventListener('mouseup', handleMouseUp)
      tableContainer.removeEventListener('mousemove', handleMouseMove)
    }
  }, [])



  return (
    <div className="card">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h2>关键备件库存记录</h2>
          {loading && <div style={{ color: '#007bff', fontSize: '14px' }}>加载中...</div>}
          {error && <div style={{ color: '#dc3545', fontSize: '14px' }}>{error}</div>}
        </div>
        <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
          {/* 行数控制 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <label style={{ fontSize: '14px', color: '#666' }}>行数：</label>
            <input
              type="number"
              value={rowInput}
              onChange={(e) => setRowInput(e.target.value)}
              style={{
                padding: '4px 8px',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                fontSize: '14px',
                width: '60px'
              }}
              min="1"
            />
            <button
              onClick={updateRowCount}
              style={{
                padding: '4px 8px',
                background: '#007bff',
                border: '1px solid #007bff',
                borderRadius: '4px',
                cursor: 'pointer',
                fontSize: '12px',
                color: 'white'
              }}
            >
              更新
            </button>
          </div>
          

          
          {/* 保存按钮 */}
          <button
            onClick={saveAllToDatabase}
            disabled={loading}
            style={{
              padding: '8px 16px',
              background: loading ? '#6c757d' : '#28a745',
              border: `1px solid ${loading ? '#6c757d' : '#28a745'}`,
              borderRadius: '6px',
              cursor: loading ? 'not-allowed' : 'pointer',
              fontSize: '14px',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              gap: '4px'
            }}
            title="保存所有数据到数据库"
          >
            {loading ? '保存中...' : '保存数据'}
          </button>
          
          {/* 导出按钮 */}
          <button
            onClick={exportToExcel}
            style={{
              padding: '8px 16px',
              background: '#6f42c1',
              border: '1px solid #6f42c1',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              gap: '4px'
            }}
            title="导出表格内容到Excel"
          >
            <Download size={16} />
            导出表格内容
          </button>
        </div>
      </div>

      {/* 表格容器 */}
      <div 
        className="inventory-table-container" 
        style={{ 
          overflowX: 'auto', 
          overflowY: 'visible',
          maxWidth: '100%',
          border: '2px solid #dee2e6', 
          borderRadius: '8px',
          cursor: 'grab',
          userSelect: 'none',
          // 自定义滚动条样式
          scrollbarWidth: 'thin',
          scrollbarColor: '#c1c1c1 #f1f1f1',
          // 移除内联webkit滚动条样式，使用CSS类代替
        }}
      >

        <table style={{ 
          width: '100%', 
          minWidth: `${tableCols * 100}px`,
          borderCollapse: 'collapse', 
          fontSize: '14px',
          background: 'white'
        }}>
          <thead>
            <tr style={{ background: '#f8f9fa' }}>
              {columnNames.map((name, colIndex) => (
                <th key={colIndex} style={{ 
                  padding: '8px', 
                  border: '1px solid #dee2e6', 
                  fontWeight: '600', 
                  textAlign: 'center', 
                  minWidth: '100px',
                  position: 'relative'
                }}>
                  {name}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {tableData.map((row, rowIndex) => (
              <tr key={rowIndex}>
                {row.map((cell, colIndex) => (
                  <td key={colIndex} style={{ 
                    padding: '8px', 
                    border: '1px solid #dee2e6', 
                    minHeight: '40px',
                    background: colIndex === 0 ? '#f8f9fa' : 'white'
                  }}>
                    {colIndex === 0 ? (
                      <div style={{ textAlign: 'center', fontWeight: '500' }}>{rowIndex + 1}</div>
                    ) : (
                      <input
                        type={colIndex === 4 || colIndex === 7 ? 'date' : 'text'}
                        value={cell}
                        onChange={(e) => updateTableData(rowIndex, colIndex, e.target.value)}
                        style={{
                          width: '100%',
                          border: 'none',
                          background: 'transparent',
                          outline: 'none',
                          fontSize: '14px',
                          padding: '4px'
                        }}
                      />
                    )}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>


    </div>
  )
}

export default KeyPartsInventory